import { Modal } from '@jecloud/ui';
import VueEvent from '@/helper/model/event';
import { saveConfigData } from '@/api';
import { useI18n } from '@common/locales';

// 对话框
export const useOpenDialog = ({ attribute, allFields, type = '' }) => {
  const I18n = useI18n().messages.zh_CN;
  // 装换数据类型，改变整体数据有用.
  allFields = JSON.parse(allFields);
  const dialogEvent = async () => {
    Modal.dialog({
      content: I18n.dialog.content,
      status: 'warning',
      icon: 'fal fa-question-circle',
      buttons: [
        {
          text: I18n.dialog.comfirm,
          type: 'primary',
          closable: false,
          handler: ({ $modal }) => {
            VueEvent.emit('closeEvent');
            VueEvent.emit('saveResult', true);
            $modal.close();
          },
        },
        {
          text: I18n.dialog.save,
          type: 'primary',
          closable: false,
          handler: ({ button, $modal }) => {
            button.disabled = true;
            // 是否是消息页面进行验证.
            if (type) {
              VueEvent.emit('validateNote');
              $modal.close();
              button.disabled = false;
              VueEvent.emit('saveResult', true);
            } else if (
              attribute === 'security-config' ||
              attribute === 'mail-config' ||
              attribute === 'team-config'
            ) {
              VueEvent.emit('securityConfigCheck');
              $modal.close();
              button.disabled = false;
            } else {
              saveConfigData({ attribute, allFields: JSON.stringify(allFields), type: '' }).then(
                VueEvent.emit('closeEvent'),
                VueEvent.emit('saveResult', true),
                VueEvent.emit('changeAllData', { item: attribute, formState: allFields }),
                Modal.notice(I18n.dialog.success, 'success'),
                $modal.close(),
                (button.disabled = false),
              );
            }
          },
        },
        {
          text: I18n.cancel,
        },
      ],
    });
  };
  return dialogEvent();
};
